package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class PermissisonInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {

        /*//权限判断逻辑
        //1.获取当前登录用户
        //Employee employee = (Employee)request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        //2.判断用户是否是超级管理员
        if(employee.isAdmin()){
            //是 = > 放行
            return true;
        }
            //否 = > 3
        //3.获取当前要执行的处理方法(controller中具体要执行的方法)
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        //4.判断该方法是否有贴自定义的权限注解
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if(annotation == null){
            //否 => 放行
            return true;
        }
            //是 => 5
        //5.获取该方法的权限表达式
        String expression = annotation.expression();
        //6.获取当前用户已经拥有的权限表达式集合
        //List<String> permissionExpression = (List<String>)request.getSession().getAttribute("EXPRESSION_IN_SESSION");
        List<String> permissionExpression = UserContext.getExpression();
        //7.判断方法的权限表达式是否在该集合中
        if(permissionExpression.contains(expression)){
            //是 => 放行
            return  true;
        }
                //否 => 8
        //8.跳转到错误提示的页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        //9.不放行*/
        return false;
    }
}
